class WsClient {
    constructor(im, url, handler, listener, heartbeatTimeout, reconnInterval) {
        this.im = im;
        this.url = url;
        this.handler = handler;
        this.listener = listener;
        this.heartbeatTimeout = heartbeatTimeout;
        this.heartbeatSendInterval = heartbeatTimeout / 2;
        this.reconnInterval = reconnInterval;
    }

    lastInteractionTime() {
        if (arguments.length == 1) {
            this.lastInteractionTimeValue = arguments[0];
        }
        return this.lastInteractionTimeValue;
    }



    /**
     * 
     */
    connect() {
        //console.log(this.url);
        let ws = new WebSocket(this.url);
        this.ws = ws;

        ws.binaryType = 'arraybuffer'; // 'blob';//
        let self = this;
        ws.onopen = function(event) {
            self.listener.onopen.call(self.listener, event, ws);
            self.lastInteractionTime(new Date().getTime());

            self.pingIntervalId = setInterval(function() { self.ping(self) }, self.heartbeatSendInterval);
            //console.log("连接成功，创建定时任务", self.pingIntervalId);
        }
        ws.onmessage = function(event) {
            //console.log(event);
            self.listener.onmessage.call(self.listener, event, ws);
            self.lastInteractionTime(new Date().getTime());
        }
        ws.onclose = function(event) {
            clearInterval(self.pingIntervalId); // clear send heartbeat task

            //console.log("连接关闭，清除定时任务", self.pingIntervalId);
            try {
                self.listener.onclose.call(self.listener, event, ws);
            } catch (error) {

            }

            self.reconn(event);
        }
        ws.onerror = function(event) {
            self.listener.onerror.call(self.listener, event, ws);
        }

        return ws;
    }

    reconn(event) {
        let self = this;
        setTimeout(function() {
            let ws = self.im.wsClient.connect();
            self.im.ws = ws;
            //console.log("已经重连", self.im);
        }, this.im.reconnInterval);
    }

    ping() {

        let iv = new Date().getTime() - this.lastInteractionTime(); // 已经多久没发消息了
        //console.log("执行心跳发送定时任务---1", this.heartbeatTimeout, this.heartbeatSendInterval, iv, this);
        if ((this.heartbeatSendInterval + iv) >= this.heartbeatTimeout) {
            //console.log("执行心跳发送定时任务---2", this, this.ws);
            this.handler.ping(this.ws);
        }
    }




    getWs() {
        return this.ws;
    }
}

export default WsClient;